﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Text;
using System.Drawing;



/// <summary>
/// CommonClass 的摘要说明
/// </summary>
namespace Util
{
    public class CommonClass
    {
        public CommonClass()
        {

        }

        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="password">明文</param>
        /// <param name="format">算法:sha1,md5</param>
        /// <returns></returns>
        public static string Encryption(string password, string format)
        {
            password = password.Trim();
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, format).Trim();
        }
        
        /// <summary>
        /// 设置页面无缓存，使用户IE后退无效
        /// </summary>
        public static void SetPageNoCatch()
        {
            HttpContext.Current.Response.Buffer = true;

            HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddHours(-1);

            HttpContext.Current.Response.Expires = 0;

            HttpContext.Current.Response.CacheControl = "no-cache";
        }
        /// <summary>
        /// 关闭窗口
        /// </summary>
        public static void CloseWindow()
        {
            HttpContext.Current.Response.Write("<script>window.close();</script>");
        }
        /// <summary>
        /// 弹出信息
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static void Alert(string msg)
        {
            HttpContext.Current.Response.Write("<script>alert('" + msg + "');</script>");
        }
        /// <summary>
        /// 弹出信息
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static void Alert(string msg, bool back)
        {
            HttpContext.Current.Response.Write("<script>alert(\"" + msg.Replace("\"", "") + "\");history.back();</script>");
        }
        /// <summary>
        /// 弹出信息并转向url
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="url"></param>
        public static void Alert(string msg, string url)
        {
            HttpContext.Current.Response.Write("<script>alert('" + msg + "');location.href='" + url + "';</script>");
        }
        /// <summary>
        /// 通过HeadText获取到某列
        /// </summary>
        /// <param name="m_DataGrid">DataGrid</param>
        /// <param name="strHeadText">列标题文本</param>
        /// <returns></returns>
        public static DataGridColumn GetDGColumnByHeadText(DataGrid m_DataGrid, string strHeadText)
        {
            foreach (DataGridColumn m_DataGridColumn in m_DataGrid.Columns)
            {
                if (m_DataGridColumn.HeaderText.Trim() == strHeadText.Trim())
                {
                    return m_DataGridColumn;
                }
            }
            return null;
        }

        /// <summary>
        /// 弹出确认信息
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static void Confirm(string msg)
        {
            HttpContext.Current.Response.Write("<script>return confirm('" + msg + "');</script>");
        }
        /// <summary>
        /// 关闭窗口
        /// </summary>
        public static void WindowClose()
        {
            HttpContext.Current.Response.Write("<script>window.close();</sc" + "ript>");
        }
        /// <summary>
        /// 关闭窗口,是否刷新父窗口
        /// </summary>
        public static void WindowClose(bool refreshParentWindow)
        {
            if (refreshParentWindow)
            {
                HttpContext.Current.Response.Write("<scr" + "ipt>opener.location.reload(); window.close();</sc" + "ript>");
            }
            else
            {

                HttpContext.Current.Response.Write("<sc" + "ript>window.close();</sc" + "ript>");
            }
        }

        /// <summary>
        /// 关闭窗口,把父窗口转向到parenturl
        /// </summary>
        public static void WindowClose(string parentUrl)
        {
            if (parentUrl != "")
            {
                HttpContext.Current.Response.Write("<scr" + "ipt>opener.location.href='" + parentUrl + "'; window.close();</sc" + "ript>");
            }
            else
            {

                HttpContext.Current.Response.Write("<sc" + "ript>window.close();</sc" + "ript>");
            }
        }

        /// <summary>
        /// 打开新窗口
        /// </summary>
        /// <param name="url">路径</param>
        public static void Open(string url)
        {
            HttpContext.Current.Response.Write("<script>window.open('" + url + "');</script>");
        }
        /// <summary>
        /// 转到其它URL
        /// </summary>
        /// <param name="url">路径</param>
        public static void Redirect(string url)
        {
            HttpContext.Current.Response.Write("<script>location.href='" + url + "';</script>");
        }
        /// <summary>
        /// 去登陆
        /// </summary>
        public static void ToLogin()
        {
            HttpContext.Current.Response.Write("<script>location.href='/default.aspx';</script>");
        }
        /// <summary>
        /// 转到其它URL
        /// </summary>
        /// <param name="url">路径</param>
        public static void Redirect(string url, bool top)
        {
            if (top)
            {
                HttpContext.Current.Response.Write("<script>top.location.href='" + url + "';</script>");
            }
            else
            {
                HttpContext.Current.Response.Write("<script>location.href='" + url + "';</script>");
            }
        }
        /// <summary>
        /// 显示错误信息并弹出信息
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string Error(string s)
        {
            return "<font color='red'></font><script>alert('" + s + "');</script>";
        }
        /// <summary>
        ///  
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ShowError(string s)
        {
            return "<font color='red'>" + s + "</font>  ";
        }
        /// <summary>
        /// 显示弹出信息
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ShowMsg(string s)
        {
            return "<font color='red'></font><script>alert('" + s + "');</script>";
        }
        /// <summary>
        /// 通过key取得配置文件中的value值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetConfigurationSetting(string key)
        {
            return System.Configuration.ConfigurationSettings.AppSettings[key];
        }
        /// <summary>
        /// 给DataGrid删除按钮添加客户端验证
        /// </summary>
        /// <param name="dg">DataGrid</param>
        /// <param name="del">删除按钮名称</param>
        public static void ItemDataBount(System.Web.UI.WebControls.DataGrid dg, string del)
        {
            for (int i = 0; i < dg.Items.Count; i++)
            {
                System.Web.UI.WebControls.LinkButton lbtn = (System.Web.UI.WebControls.LinkButton)dg.Items[i].FindControl(del);

                if (lbtn != null)
                {
                    lbtn.Attributes.Add("onclick", "javascript:return confirm('确定删除此项吗？');");
                }
            }
        }

        /// <summary>
        /// 给Repeater删除按钮添加客户端验证
        /// </summary>
        /// <param name="rpt">Repeater</param>
        /// <param name="del">删除按钮名称</param>
        public static void ItemDataBount(System.Web.UI.WebControls.Repeater rpt, string del)
        {
            for (int i = 0; i < rpt.Items.Count; i++)
            {
                System.Web.UI.WebControls.LinkButton lbtn = (System.Web.UI.WebControls.LinkButton)rpt.Items[i].FindControl(del);

                if (lbtn != null)
                {
                    lbtn.Attributes.Add("onclick", "javascript:return confirm('确定删除此项吗？');");
                }
            }
        }

        /// <summary>
        /// 给Repeater删除按钮添加客户端验证
        /// </summary>
        /// <param name="rpt">Repeater</param>
        /// <param name="del">删除按钮名称</param>
        /// <param name="del">弹出的信息内容</param>
        public static void ItemDataBount(System.Web.UI.WebControls.Repeater rpt, string del, string msg)
        {
            for (int i = 0; i < rpt.Items.Count; i++)
            {
                System.Web.UI.WebControls.LinkButton lbtn = (System.Web.UI.WebControls.LinkButton)rpt.Items[i].FindControl(del);

                if (lbtn != null)
                {
                    lbtn.Attributes.Add("onclick", "javascript:return confirm('" + msg + "');");
                }
            }
        }

        /// <summary>
        /// 给GridView删除按钮添加客户端验证
        /// </summary>
        /// <param name="dg">GridView</param>
        /// <param name="del">删除按钮名称</param>
        public static void ItemDataBount(System.Web.UI.WebControls.GridView gv, string del)
        {
            for (int i = 0; i < gv.Rows.Count; i++)
            {
                System.Web.UI.WebControls.LinkButton lbtn = (System.Web.UI.WebControls.LinkButton)gv.Rows[i].FindControl(del);

                if (lbtn != null)
                {
                    lbtn.Attributes.Add("onclick", "javascript:return confirm('确定删除此项吗？');");
                }
            }
        }
        /// <summary>
        ///当前记录的行KeyID
        /// </summary>
        /// <param name="gv"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        public static int GetCuurentID(System.Web.UI.WebControls.GridView gv, int rowIndex)
        {
            return Convert.ToInt32(gv.DataKeys[rowIndex].Value);
        }
        /// <summary>
        ///通过URL下载网页HTML,返回HTML代码
        /// </summary>
        /// <param name="url">要下载的网页的路径</param>
        /// <returns></returns>
        public static string GetStrByUrl(string url)
        {
            try
            {
                string source = "";
                WebClient client = new WebClient();
                Stream sr = client.OpenRead(url);
                if (sr != null)
                {
                    StreamReader streamr = new StreamReader(sr, Encoding.Default);
                    source = streamr.ReadToEnd();
                    sr.Close();
                    streamr.Close();
                }
                return source.Replace("\n", "").Replace("\t", "").Replace("\r", "");
            }
            catch (System.InvalidOperationException ex)
            {
                return "";
                throw ex;
            }
        }
        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static string ReadFileToString(string path)
        {
            StreamReader sr = new StreamReader(path, System.Text.Encoding.Default);
            if (sr != null)
            {
                string s = sr.ReadToEnd();
                sr.Close();
                return s;
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 把字符存储为文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="content">内容</param>
        public static void SaveToFile(string path, string content)
        {
            StreamWriter sw = new StreamWriter(path, false, System.Text.Encoding.Default);
            sw.Write(content);
            sw.Close();
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="postfile"></param>
        /// <param name="savefilename">文件绝对路径，如e:\ss\ssdsds.gif</param>
        /// <returns></returns>
        public static string SaveImgFile(HttpPostedFile postfile, string savefilename)
        {
            //if (postfile.ContentType == "image/pjpeg" || postfile.ContentType == "image/gif" || postfile.ContentType == "image/bmp")
            //{
            string dir = savefilename.Substring(0, savefilename.LastIndexOf('\\'));
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            postfile.SaveAs(savefilename);
            return "ok";
            //}
            //else
            //{
            //    return "文件格式不正确";
            //}

        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">文件所在网络上的地址</param>
        /// <param name="filepath">保存在本地的地址</param>
        public static void DownFileByUrl(string url, string filepath)
        {
            WebClient client = new WebClient();
            client.DownloadFile(url, filepath); 
        }

        /// <summary>
        /// DataGrid全选,全不选;用法:CommonClass.BoundCheck(dg,"chk","chkall",out str,out function);
        /// if(!Page.IsClientScriptBlockRegistered(function)){Page.RegisterClientScriptBlock(function,str);}
        /// </summary>
        /// <param name="dg">datagrid 控件</param>
        /// <param name="chk"></param>
        /// <param name="dgchkall">全选控件</param>
        /// <param name="regScript"></param>
        /// <param name="function"></param>
        public static void BoundCheckBox(System.Web.UI.WebControls.DataGrid dg, string chk, string dgchkall, out string regScript, out string function)
        {
            regScript = "";
            System.Text.StringBuilder strScript = new System.Text.StringBuilder();
            if (dg.Controls.Count > 0)
            {
                foreach (DataGridItem item in dg.Controls[0].Controls)
                {
                    if (item.ItemType == ListItemType.Header)
                    {
                        CheckBox chkAll = (CheckBox)item.FindControl(dgchkall);
                        if (chkAll != null)
                        {
                            strScript = new System.Text.StringBuilder("<script language='javascript'> \n");
                            strScript.Append("    function checkStatus() { \n");
                            strScript.Append("        var bAll = true; \n");
                            strScript.Append("        bAll = document.all('" + chkAll.ClientID + "').checked; \n");

                            for (int i = 0; i < dg.Items.Count; i++)
                            {
                                CheckBox chk1 = (CheckBox)dg.Items[i].FindControl(chk);
                                if (chk1 != null)
                                {
                                    strScript.Append("        document.all('" + dg.Items[i].FindControl(chk).ClientID + "').checked = bAll; \n");
                                }
                            }
                            strScript.Append("    } \n");
                            strScript.Append("</script> \n");

                            chkAll.Attributes.Add("onclick", "checkStatus()");
                        }
                    }
                }
            }
            function = "checkStatus";
            regScript = strScript.ToString();
        }
        /// <summary>
        /// GridView全选,全不选;用法:CommonClass.BoundCheck(gv,"chk","chkall",out str,out function);//在PreRender事件下调用后再用下面的代码
        /// if(!Page.IsClientScriptBlockRegistered(function)){Page.RegisterClientScriptBlock(function,str);}
        /// </summary>
        /// <param name="dg">datagrid 控件</param>
        /// <param name="chk"></param>
        /// <param name="dgchkall">全选控件</param>
        /// <param name="regScript"></param>
        /// <param name="function"></param>
        public static void BoundCheckBox(System.Web.UI.WebControls.GridView gv, string chk, string chkall, out string regScript, out string function)
        {
            regScript = "";
            System.Text.StringBuilder strScript = new System.Text.StringBuilder();
            if (gv.Controls.Count > 0)
            {

                CheckBox gvchkall = (CheckBox)(gv.HeaderRow.FindControl(chkall));
                if (gvchkall != null)
                {

                    strScript = new System.Text.StringBuilder("<script language='javascript'> \n");
                    strScript.Append("    function checkStatus() { \n");
                    strScript.Append("        var bAll = true; \n");
                    strScript.Append("        bAll = document.all('" + gvchkall.ClientID + "').checked; \n");

                    for (int i = 0; i < gv.Rows.Count; i++)
                    {
                        CheckBox chk1 = (CheckBox)gv.Rows[i].FindControl(chk);
                        if (chk1 != null)
                        {
                            strScript.Append("        document.all('" + gv.Rows[i].FindControl(chk).ClientID + "').checked = bAll; \n");
                        }
                    }
                    strScript.Append("    } \n");
                    strScript.Append("</script> \n");

                    gvchkall.Attributes.Add("onclick", "checkStatus()");
                }
            }
            function = "checkStatus";
            regScript = strScript.ToString();
        }

        /// <summary>
        /// 当前时间作为文件名称
        /// </summary>
        /// <returns></returns>
        public static string GetFileName()
        {
            return System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();
        }


        /// <summary>
        /// 分页代码
        /// </summary>
        /// <param name="total">记录数</param>
        /// <param name="pagesize">每页显示记录数</param>
        /// <param name="webname">网页名称:有其它get参数时后面加"&",没有时加"?"</param>
        /// <param name="index">当前页</param>
        /// <param name="barnum">页码数量</param>
        /// <returns></returns>
        public static string PageBar(int total, int pagesize, string webname, int index, int barnum)
        {
            string pagebar = " ";
            int re = 0;
            int pages = Math.DivRem(total, pagesize, out re);
            if (re > 0)
            {
                pages = pages + 1;
            }

            string first = " <a href=\"" + webname + "\">首页</a>&nbsp; ";
            string last = "&nbsp;&nbsp;<a href=\"" + webname + "index=" + pages.ToString() + "\">尾页</a>";
            int sep = barnum / 2;
            //上一页,下一页
            int prepage = index - 1;
            int nextpage = index + 1;
            string strprepage = "";
            string strnextpage = "";
            if (prepage > 0)
            {
                //上一页
                strprepage = "<a href=\"" + webname + "index=" + prepage.ToString() + "\"> [上一页]</a>&nbsp; \n";
            }

            if (nextpage < pages + 1)
            {
                //下一页
                strnextpage = "<a href=\"" + webname + "index=" + nextpage.ToString() + "\"> [下一页]</a> &nbsp;\n";
            }

            if (pages < barnum)
            {
                for (int i = 1; i < pages + 1; i++)
                {
                    if (i != index)
                    {
                        pagebar += "<a href=\"" + webname + "index=" + i.ToString() + "\"> [" + i.ToString() + "]</a> &nbsp;  \n";
                    }
                    else
                    {
                        pagebar += "&nbsp;[" + i.ToString() + "]&nbsp;\n";
                    }
                }
                //当页码数量小于barnum时不显示首页和尾页
                first = "";
                last = "";
            }
            else
            {
                int pre1 = index - sep;//前sep页
                if (pre1 < 1)
                {
                    pre1 = 1;
                }
                int next1 = index + sep; ;//后sep页
                if (next1 > pages)
                {
                    next1 = pages;
                }

                for (int i = pre1; i < next1 + 1; i++)
                {
                    if (i != index)
                    {
                        pagebar += "<a href=\"" + webname + "index=" + i.ToString() + "\"> [" + i.ToString() + "]</a> &nbsp; \n";
                    }
                    else
                    {
                        pagebar += "&nbsp;[" + i.ToString() + "]&nbsp;\n";
                    }
                }

            }
            pagebar = first + strprepage + pagebar + strnextpage + last;
            return pagebar;
        }


        /// <summary>
        /// 分页代码
        /// </summary>
        /// <param name="total">记录数</param>
        /// <param name="pagesize">每页显示记录数</param>
        /// <param name="webname">网页名称:有其它get参数时后面加"&",没有时加"?"</param>
        /// <param name="index">当前页</param>
        /// <param name="barnum">页码数量</param>
        /// <returns></returns>
        public static string PageBar(int total, int pagesize, string webname, int index, int barnum, string extend)
        {
            string pagebar = " ";
            int re = 0;
            int pages = Math.DivRem(total, pagesize, out re);
            if (re > 0)
            {
                pages = pages + 1;
            }

            string first = " <a href=\"" + webname + "\">首页</a>&nbsp; ";
            string last = "&nbsp;&nbsp;<a href=\"" + webname + "_" + pages.ToString() + extend + "\">尾页</a>";
            int sep = barnum / 2;
            //上一页,下一页
            int prepage = index - 1;
            int nextpage = index + 1;
            string strprepage = "";
            string strnextpage = "";
            if (prepage > 0)
            {
                //上一页
                strprepage = "<a href=\"" + webname + "_" + prepage.ToString() + extend + "\"> [上一页]</a>&nbsp; \n";
            }

            if (nextpage < pages + 1)
            {
                //下一页
                strnextpage = "<a href=\"" + webname + "_" + nextpage.ToString() + extend + "\"> [下一页]</a> &nbsp;\n";
            }

            if (pages < barnum)
            {
                for (int i = 1; i < pages + 1; i++)
                {
                    if (i != index)
                    {
                        pagebar += "<a href=\"" + webname + "_" + i.ToString() + extend + "\"> [" + i.ToString() + "]</a> &nbsp;  \n";
                    }
                    else
                    {
                        pagebar += "&nbsp;[" + i.ToString() + "]&nbsp;\n";
                    }
                }
                //当页码数量小于barnum时不显示首页和尾页
                first = "";
                last = "";
            }
            else
            {
                int pre1 = index - sep;//前sep页
                if (pre1 < 1)
                {
                    pre1 = 1;
                }
                int next1 = index + sep; ;//后sep页
                if (next1 > pages)
                {
                    next1 = pages;
                }

                for (int i = pre1; i < next1 + 1; i++)
                {
                    if (i != index)
                    {
                        pagebar += "<a href=\"" + webname + "_" + i.ToString() + extend + "\"> [" + i.ToString() + "]</a> &nbsp; \n";
                    }
                    else
                    {
                        pagebar += "&nbsp;[" + i.ToString() + "]&nbsp;\n";
                    }
                }

            }
            pagebar = first + strprepage + pagebar + strnextpage + last;
            return pagebar;
        }
        /// <summary>
        /// 去掉字符串中的HTML
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string RepalceHTML(string source)
        {
            source = Regex.Replace(source, "<(\\s|\\S)+?>", "", RegexOptions.IgnoreCase);
            return source;
        }

        public void DropdowListBound(System.Web.UI.WebControls.DropDownList ddl, System.Data.DataView dv, string valueField, string textField)
        {
            ddl.DataSource = dv;
            ddl.DataValueField = valueField;
            ddl.DataTextField = textField;
            ddl.DataBind();
        }
        public void DataBound(System.Web.UI.WebControls.DataGrid dg, System.Data.DataView dv)
        {
            dg.DataSource = dv;
            dg.DataBind();
        }
        public void DataBound(System.Web.UI.WebControls.Repeater rpt, System.Data.DataView dv)
        {
            rpt.DataSource = dv;
            rpt.DataBind();
        }
        public void DataBound(System.Web.UI.WebControls.DataList dl, System.Data.DataView dv)
        {
            dl.DataSource = dv;
            dl.DataBind();
        }
        public static string ServerFile(string strpath)
        {
            return System.Web.HttpContext.Current.Server.MapPath(strpath);
        }
        public static string HtmlDeCode(string str)
        {
            return System.Web.HttpContext.Current.Server.HtmlDecode(str);
        }
        public static string HtmlEnCode(string str)
        {
            return System.Web.HttpContext.Current.Server.HtmlEncode(str);
        }
        public static string UrlDeCode(string str)
        {
            return System.Web.HttpContext.Current.Server.UrlDecode(str);
        }
        public static string UrlEnCode(string str)
        {
            return System.Web.HttpContext.Current.Server.UrlEncode(str);
        }
        /// <summary>
        /// 返回数字的汉字
        /// </summary>
        /// <param name="inti"></param>
        /// <returns></returns>
        public static string GetHan(int inti)
        {
            string[] c = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", };
            for (int i = 0; i < c.Length; i++)
            {
                if (inti == i + 1)
                {
                    return c[i];
                }
            }
            return inti.ToString();
        }
        public static void CreateCookie(string cookiename)
        {
            HttpCookie cook = new HttpCookie(cookiename);
            cook["hits"] = "00";
            cook.Expires = DateTime.Now.AddDays(1);
            HttpContext.Current.Response.Cookies.Add(cook);
        }
        /// <summary>
        /// 替换掉不要的内容
        /// </summary>
        /// <param name="input"></param>
        /// <param name="reg">正则表达式</param>
        /// <returns></returns>
        public static string ClearByRegex(string input, string reg)
        {
            return Regex.Replace(input, reg, "", RegexOptions.IgnoreCase);
        }
        /// <summary>
        /// 返回整型查询字符串的值,异常返回0
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static int GetIntQueryString(string name)
        {
            try
            {

                if (HttpContext.Current.Request.QueryString[name] != null)
                {
                    return Convert.ToInt32(HttpContext.Current.Request.QueryString[name].ToString());

                }
                else if (HttpContext.Current.Request.Form[name] != null)
                {
                    return Convert.ToInt32(HttpContext.Current.Request.Form[name].ToString());

                }
                else
                {
                    return 0;
                }
            }
            catch
            {
                return 0;
            }
        }
        /// <summary>
        /// 返回查询字符串的字符串,异常返回undefined
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetStringQueryString(string name)
        {
            try
            {
                if (HttpContext.Current.Request.QueryString[name] != null)
                {
                    return HttpContext.Current.Request.QueryString[name].ToString(); ;

                }
                else if (HttpContext.Current.Request.Form[name] != null)
                {
                    return HttpContext.Current.Request.Form[name].ToString();

                }
                else
                {
                    return "";
                }
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 返回页码,小于1则返回1
        /// </summary>
        /// <returns></returns>
        public static int GetIndex()
        {
            try
            {
                int index = Convert.ToInt32(HttpContext.Current.Request.QueryString["index"]);
                if (index < 1)
                {
                    return 1;
                }
                return index;
            }
            catch
            {
                return 1;
            }
        }
        /// <summary>
        /// 设置下拉列表的默认选项值
        /// </summary>
        /// <param name="ddl"></param>
        /// <param name="selectValue"></param>
        public static void SetDropDownList(DropDownList ddl, string selectValue)
        {
            if (selectValue == null)
            {
                return;
            }
            for (int i = 0; i < ddl.Items.Count; i++)
            {
                if (ddl.Items[i].Value == selectValue)
                {
                    ddl.SelectedIndex = i;
                    break;
                }
            }
        }
        /// <summary>
        /// 根据Text设置下拉列表的默认选项值
        /// </summary>
        /// <param name="ddl"></param>
        /// <param name="selectValue"></param>
        public static void SetDropDownListByText(DropDownList ddl, string text)
        {
            if (text == null)
            {
                return;
            }

            for (int i = 0; i < ddl.Items.Count; i++)
            {
                if (ddl.Items[i].Text == text)
                {
                    ddl.SelectedIndex = i;
                    return;

                }
            }
            for (int i = 0; i < ddl.Items.Count; i++)
            {
                if (ddl.Items[i].Text.IndexOf(text) > -1)
                {
                    ddl.SelectedIndex = i;
                    return;

                }
            }
        }

        /// <summary>
        /// 根据Text设置下拉列表的默认选项值
        /// </summary>
        /// <param name="ddl"></param>
        /// <param name="text"></param>
        /// <param name="defaultText">找不到就设置默认的值</param>
        /// <param name="defaultValue"></param>
        public static void SetDropDownListByText(DropDownList ddl, string text, string defaultText, string defaultValue)
        {
            if (text == null)
            {
                return;
            }
            for (int i = 0; i < ddl.Items.Count; i++)
            {
                if (ddl.Items[i].Text == text)
                {
                    ddl.SelectedIndex = i;
                    return;

                }
            }
            for (int i = 0; i < ddl.Items.Count; i++)
            {
                if (ddl.Items[i].Text.IndexOf(text) > -1)
                {
                    ddl.SelectedIndex = i;
                    return;

                }
            }
            ddl.Items.Add(new ListItem(defaultText, defaultValue));
            ddl.SelectedValue = defaultValue;
        }

        /// <summary>
        /// 返回用户ID
        /// </summary>
        /// <returns></returns>
        public static int GetUserID()
        {
            if (HttpContext.Current.Session["uid"] != null)
            {
                return Convert.ToInt32(HttpContext.Current.Session["uid"]);
            }
            else
            {
                return 0;
            }
        }
        public static string GetMyName()
        {
            if (HttpContext.Current.Session["FullName"] != null)
            {
                return HttpContext.Current.Session["FullName"].ToString();
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 返回日期的短日期"0001-1-1"返回为空
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string GetNullDateTime(DateTime dt)
        {
            try
            {
                if (dt.ToShortDateString() == "0001-1-1")
                {
                    return "";
                }

                else
                {
                    return dt.ToShortDateString();
                }
            }
            catch
            {
                return "";
            }
        }

        ///   <summary>      
        ///   说明：返回两个日期之间的时间间隔
        ///   单位：深圳皇锐科技
        ///   添加：许宏凯
        ///   日期：2009-9-2
        ///   </summary>      
        ///   <param   name="Date1">开始日期</param>      
        ///   <param   name="Date2">结束日期</param>      
        ///   <param   name="Interval">间隔标志（y：年份间隔、M：月份间隔、d：天数间隔、h：小时间隔、m：分钟间隔、s：秒钟间隔、ms：微秒间隔）</param>      
        ///   <returns>返回间隔标志指定的时间间隔</returns>      
        public static int DateDiff(System.DateTime Date1, System.DateTime Date2, string Interval)
        {
            double dblYearLen = 365;//年的长度，365天      
            double dblMonthLen = (365 / 12);//每个月平均的天数      
            System.TimeSpan objT;
            objT = Date2.Subtract(Date1);
            switch (Interval)
            {
                case "y"://返回日期的年份间隔      
                    return System.Convert.ToInt32(objT.Days / dblYearLen);
                case "M"://返回日期的月份间隔      
                    return System.Convert.ToInt32(objT.Days / dblMonthLen);
                case "d"://返回日期的天数间隔      
                    return objT.Days;
                case "h"://返回日期的小时间隔      
                    return objT.Hours;
                case "m"://返回日期的分钟间隔      
                    return objT.Minutes;
                case "s"://返回日期的秒钟间隔      
                    return objT.Seconds;
                case "ms"://返回时间的微秒间隔      
                    return objT.Milliseconds;
                default:
                    break;
            }
            return 0;
        }

        /// <summary>
        ///   说明：指定长度和来格式化字符串，可指定替代字符传
        ///   单位：深圳皇锐科技
        ///   添加：许宏凯
        ///   日期：2009-9-2
        /// </summary>
        /// <param name="formatStr">需格式化的字符串</param>
        /// <param name="strLength">格式化长度,>=0</param>
        /// <param name="replaceStr">超过长度后需要替代的字符串,可为空</param>
        /// <returns></returns>
        public static string FormatString(string formatStr, int strLength, string replaceStr)
        {
            if (formatStr.Length <= strLength)
                return formatStr;
            else
                return formatStr.Substring(0, strLength) + replaceStr;
        }

        public static string GetWebMainUrl
        {
            get { return HttpContext.Current.Request.ApplicationPath; }
        }

    }
}
